﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Data.SQLite;

namespace GitMirrors
{
    public partial class GitMain : Form
    {
        public GitMain()
        {
            InitializeComponent();
        }

        private void searchBtn_Click(object sender, EventArgs e)
        {
            try
            {
                string search = searchBox.Text.Trim();
                if (string.IsNullOrWhiteSpace(search))
                {
                    showError(Messages.EMPTY);
                    return;
                }

                if (search.EndsWith(".git"))
                {
                    search = search.Substring(0, search.Length - 4);
                }

                clearAllData();
                List<GitItem> items = getAllData(search);
                renderListView(items);
            } catch (Exception ex)
            {
                showError(ex.Message);
            }      
        }

        // 错误提示
        void showError(string msg)
        {
            MessageBox.Show(msg, Messages.TIP, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        // 获取全部数据
        List<GitItem> getAllData(string key)
        {
            List<GitItem> items = new List<GitItem>();
            try
            {
                using (var connection = new SQLiteConnection("Data Source=mirrors.db"))
                {
                    connection.Open();

                    var command = connection.CreateCommand();
                    command.CommandText =
                        @"
                        SELECT * 
                        FROM github
                        WHERE title like $like_key
                        OR github = $key
                        LIMIT 20
                    ";
                    command.Parameters.AddWithValue("$like_key", $"%{key}%");
                    command.Parameters.AddWithValue("$key", key);

                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            GitItem item = new GitItem(reader.GetString(1), reader.GetString(2), reader.GetString(3));
                            items.Add(item);
                        }
                    }
                }
            }
            catch (SQLiteException err)
            {
                showError(err.Message);
            }

            return items;
        }

        void renderListView(List<GitItem> items)
        {
            int id = 1;

            searchList.BeginUpdate();
            foreach(var item in items)
            {
                ListViewItem lvItem = new ListViewItem(id.ToString());
                lvItem.SubItems.Add(new ListViewItem.ListViewSubItem(lvItem, item.title));
                lvItem.SubItems.Add(new ListViewItem.ListViewSubItem(lvItem, item.gitee));
                lvItem.SubItems.Add(new ListViewItem.ListViewSubItem(lvItem, item.github));
                searchList.Items.Add(lvItem);
                id++;
            }
            searchList.EndUpdate();

            if (id > 1)
            {
                searchList.Items[0].Selected = true;
            }
        }

        private void searchList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (searchList.SelectedItems.Count == 0)
            {
                return;
            }
            ListViewItem.ListViewSubItemCollection subItems = searchList.SelectedItems[0].SubItems;
            string gitee = subItems[2].Text + ".git";
            string github = subItems[3].Text;
            if (github.EndsWith("/"))
            {
                github = github.Substring(0, github.Length - 1) + ".git";
            } else
            {
                github = github + ".git";
            }
            cloneBox.Text = $"git clone {gitee}";
            configBox.Text = $"git config --global url.\"{gitee}\".insteadof \"{github}\"";
        }

        private void clearAllData()
        {
            searchList.Items.Clear();
            cloneBox.Clear();
            configBox.Clear();
        }
    }

    class GitItem
    {
        public string title;
        public string gitee;
        public string github;

        public GitItem()
        {

        }

        public GitItem(string title, string gitee, string github)
        {
            this.title = title;
            this.gitee = gitee;
            this.github = github;
        }
    }
}
